package com.laoda.ikun_food.controller.admin.rest;

import com.laoda.ikun_food.entity.vo.ResponseData;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api/admin/file")
public class FileRestController {

    @PostMapping("/upload")
    public ResponseData upload(MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            return ResponseData.err("empty file");
        }
        String fileName = file.getOriginalFilename();
        // 上传文件要重命名，重名会覆盖现有文件
        assert fileName != null;
        String ext = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + ext;

        String uploadDir = "/upload/";
        String realPath = request.getServletContext().getRealPath(uploadDir)+newFileName;
        System.out.println(realPath);
        File uploadDirFile = new File(realPath);
        // 如果文件路径不存在，需要创建
        if (!uploadDirFile.getParentFile().exists()) {
            uploadDirFile.getParentFile().mkdirs();
        }
        // 把文件从本地传输到服务器
        file.transferTo(uploadDirFile);
        // 还可以把文件上传到OSS云存储，保证服务器重启后不丢失
        // 具体参见相关API文档
        return ResponseData.ok().data(uploadDir+newFileName);
    }
}
